from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer
import csv
from Adtection.Adtection import Adtection
from .findNewest import find_new_file

class heartRateConsumer(WebsocketConsumer):
    

    
    def websocket_connect(self,message):#有客户端向websocket发送连接请求时自动触发
        
        self.accept() #允许建立链接
        dir = 'D:\\ftp'
        newest = find_new_file(dir)
        
        target=[]
        with open(newest) as f:
            f_csv = csv.reader(f) #turns the csv file into a list of lists.
            print(f_csv)
            for i in f_csv:
                target.append(int(i[0]))
                self.send(i[0])
            f.close()
        adtection = Adtection()
        
        self.send(adtection.predict(target))


    def websocket_receive(self, message): #浏览器基于websocket向后端发送数据，自动触发接收消息
        self.send("1")
    

    def websocket_disconnect(self, message):#客户端主动断开连接时自动触发
        raise StopConsumer()